package com.qf.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.qf.entity.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("login")
    public String login(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        User user = service.findByName(username);
        if (user != null && user.getUserPassword().equals(SecureUtil.md5(request.getParameter("password") + user.getUserSalt()))) {
            session.setAttribute("name", user.getUserName());
            String url = (String) session.getAttribute("url");
            if (url == null) {
                return "forward:/index";
            }
            return url;
        }
        session.setAttribute("err", "账号不存在或者密码错误");
        return "forward:/login.jsp";
    }

    @RequestMapping("out")
    public String out(HttpServletRequest request) {
        request.getSession().removeAttribute("name");
        return "forward:/index";
    }

    @RequestMapping("register")
    public String register(String username, @RequestParam(defaultValue = "123") String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (username == null || password == null) {
            session.setAttribute("errs", "请输入有效信息");
            return "forward:/zc.jsp";
        }
        String key = RandomUtil.randomString(3);
        String passwordKey = SecureUtil.md5(password + key);
        User byIb = service.findByName(username);
        if (byIb == null) {
            int i = service.addUser(username, passwordKey, key);
            if (i != -1) {
                request.getSession().setAttribute("name", username);
                String url = (String) session.getAttribute("url");
                if (url == null) {
                    return "forward:/index";
                }
                return url;
            } else {
                session.setAttribute("errs", "请输入有效信息");
            }
        }
        session.setAttribute("err", "此账号已被注册");
        return "forward:/zc.jsp";
    }
}
